package related

import (
	"fmt"

	"github.com/jinzhu/gorm"
)

// type User1 struct {
// 	Id   int
// 	Name string
// 	Age  int
// 	Addr string
// }

// type GradeInfo struct {
// 	Grade int
// 	Class int
// 	User  User1 `form:"ForeignKey:UId;AssociationForeignkey:Id"`
// 	UId   int
// }

type User3 struct {
	Id         int
	Name       string
	Age        int
	Addr       string
	GradeInfo3 []GradeInfo3 `gorm:"many2many:User2GradeInfo"`
}

type GradeInfo3 struct {
	Id    int
	Grade int
	Class int
	Name  string
}

func CreateManyToMany(db *gorm.DB) {
	db.AutoMigrate(&User3{}, &GradeInfo3{})
	//创建one_to_one
	user := User3{
		Name: "xiaosan",
		Age:  11,
		Addr: "湖北",
		GradeInfo3: []GradeInfo3{
			{Grade: 2, Class: 3},
			{Grade: 5, Class: 6},
			{Grade: 7, Class: 8},
		},
	}

	db.Create(&user)
}

func QueryManyToMany(db *gorm.DB) {
	//创建one_to_Many
	//第一种查询方式
	var user User3

	db.Preload("GradeInfo3").Find(&user, 1)
	fmt.Println(user)

	//第二种查询方式
	var user1 User3
	db.First(&user1, 1)

	db.Model(&user1).Association("GradeInfo3").Find(&user1.GradeInfo3)

	fmt.Println(user1)

	//第三种查询方式
	// var user4 User2
	// db.First(&user4, 1)
	// var grade3 []GradeInfo2
	// db.Model(&user4).Related(&grade3, "GradeInfo2")

	// fmt.Println(user4)
	// fmt.Println(grade3)
}

func UpdateManyToMany(db *gorm.DB) {
	//创建one_to_one
	var user User3
	db.Preload("GradeInfo3").Find(&user, 1)

	db.Model(&user.GradeInfo3).Where("Id = ?", 2).Update("Grade", 7)
	fmt.Println(user)
}

func DelManyToMany(db *gorm.DB) {
	//创建one_to_one
	var user User3
	db.Preload("GradeInfo2").Find(&user, 1)
	db.Where("Id=?", 3).Delete(&user.GradeInfo3)
	fmt.Println(user)
}
